import dayjs from "dayjs";

const emptyText = "--";

export function isDateKey(format) {
  return ["date", "time", "dataTime", "toSale"].includes(format);
}

/**
 * 根据时间跟当前时间的情况返回格式化，同一年则不展示年，同一天则不展示天
 * @param {*} time 时间配置
 * @returns String
 */
export function getToSaleFormat(time) {
  if (time) {
    let now = dayjs();
    time = dayjs(time);

    if (now.year() === time.year()) {
      if (now.month() === time.month() && now.date() === time.date()) {
        return "HH:mm:ss";
      } else {
        return "MM/DD HH:mm:ss";
      }
    }
  }

  return "YYYY/MM/DD HH:mm:ss";
}

export function normaliseFormat(format, options = { endOf: "" }) {
  if (!(typeof format === "string")) {
    return "";
  }

  switch (format) {
    case "date":
      format = "YYYY-MM-DD";
      break;
    case "time":
      format = "HH:mm:ss";
      break;
    case "dateTime":
      format = "YYYY-MM-DD HH:mm:ss";
      break;
    case "toSale":
      format = getToSaleFormat(options.time);
      // 开售时间默认到分钟
      options.endOf = options.endOf || "mm";
      break;
    default:
      break;
  }

  // end 配置 格式到哪里结束  如 格式为 HH:mm:ss， end 为 mm 则返回 HH:mm
  if (options.endOf) {
    let parts = format.split(options.endOf);

    if (parts[1]) {
      format = parts[0] + options.endOf;
    }
  }

  return format;
}

/**
 * 格式化日期
 * @param {*} time 时间
 * @param {*} format 格式 有枚举类型
 * @param {*} options 选项 endOf 配置到哪里结束。
 * @returns String
 */
export function formatTime(time, format, options = {}) {
  if (!time) {
    return emptyText;
  }

  time = dayjs(time);

  if (!time) {
    return emptyText;
  }

  return time.format(normaliseFormat(format, Object.assign({ time }, options)));
}

export function isFuture(time) {
  return time && dayjs().isBefore(dayjs(time));
}
